% This m-script uses the reduced-form coefficients from bootstrap samples
% to calculate the weight matrix to be used in CMD estimation as well as
% the subsequent specification test (test of over-identification)
% Input: 
% --- Brcm: a 6-D array with dimension 2-2-K-lb-lb-B that records
%           reduced form coefficients from each bootstrap sample
% Output:
% --- 2K-by-2K covariance matrix 
function wm = calWM(i,j,Brcm),
B = size(Brcm,6);  K = size(Brcm,3); lg = size(Brcm,4);       
% wm = zeros(K,2*lg,2*lg);
TM = []; 
for bi = 1:B, % loop in bootstrap samples
    rTM = []; 
    for ki = 1:K, % loop in indvidual characteristics
        % avg direct effects and contextual effects within group
        tm = squeeze(Brcm(i,j,ki,:,:,bi));
        rTM = [rTM , mean(diag(tm))  mean(mean(tm.*(ones(lg,lg)-eye(lg))))];             
    end;
    TM = [TM ; rTM];
end;
wm = cov(TM)\eye(2*K); 